package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;


import com.github.pagehelper.PageHelper;
import com.heima.common.constants.WemediaConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.NewsListDto;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsAndAuthorName;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.common.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.NewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmNewsTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description TODO
 * @Author bo.li
 * @Date 2023/3/16 11:11
 * @Version 1.0
 */
@Service
@Slf4j
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    @Autowired
    private WmMaterialMapper materialMapper;
    @Autowired
    private NewsAutoScanService newsAutoScanService;
    @Autowired
    private WmNewsTaskService wmNewsTaskService;
    @Autowired
    private WmNewsMapper wmNewsMapper;


    @Override
    public ResponseResult pageList(WmNewsPageReqDto reqDto) {
        //检查查询
        reqDto.checkParam();

        IPage page = new Page(reqDto.getPage(), reqDto.getSize());
        //构造查询条件
        LambdaQueryWrapper<WmNews> queryWrapper = new LambdaQueryWrapper<>();
        //状态
        queryWrapper.eq(reqDto.getStatus() != null, WmNews::getStatus, reqDto.getStatus());
        //关键字
        queryWrapper.like(!StringUtils.isEmpty(reqDto.getKeyword()), WmNews::getTitle, reqDto.getKeyword());
        //频道
        queryWrapper.eq(reqDto.getChannelId() != null, WmNews::getChannelId, reqDto.getChannelId());
        //日期
        if (reqDto.getBeginPubDate() != null && reqDto.getEndPubDate() != null) {
            queryWrapper.between(WmNews::getCreatedTime, reqDto.getBeginPubDate(), reqDto.getEndPubDate());
        }
        //userid
        queryWrapper.eq(WmNews::getUserId, WmThreadLocalUtil.getUser().getId());
        //排序
        queryWrapper.orderByDesc(WmNews::getCreatedTime);

        page(page, queryWrapper);

        ResponseResult result = new PageResponseResult(reqDto.getPage(), reqDto.getSize(), (int) page.getTotal());
        result.setData(page.getRecords());

        return result;
    }

    @Override
    public ResponseResult submit(WmNewsDto newsDto) {
        //保存文章
        WmNews wmNews = saveOrUpdate(newsDto);
        if (wmNews.getStatus() == WmNews.Status.NORMAL.getCode()) {
            log.info("保存为草稿，不再执行");
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        //关联内容和素材关系
        //提前文章内容的图片
        List<String> contentPics = getContentUrl(newsDto.getContent());
        saveMetialForContent(wmNews, contentPics);

        //关联封面图片和素材关系
        saveMetialForCover(wmNews, newsDto, contentPics);

        if (newsDto.getPublishTime() != null) {
            wmNewsTaskService.addTask(wmNews);
        } else {
            //审核
            newsAutoScanService.newsScan(wmNews);
        }

        log.info("我就是证明我要先执行的");

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 保存封面图片和素材的关系
     *
     * @param wmNews
     * @param contentPics
     * @param newsDto
     */
    private void saveMetialForCover(WmNews wmNews, WmNewsDto newsDto, List<String> contentPics) {
        List<String> images = newsDto.getImages();
        //如果是自动
        if (newsDto.getType() == WemediaConstants.TYPE_AUTO) {
            //多图
            if (contentPics.size() > 3) {
                wmNews.setType(WemediaConstants.TYPE_MANY);
                images = contentPics.stream().limit(3).collect(Collectors.toList());
            } else if (contentPics.size() >= 1 && contentPics.size() < 3) {
                wmNews.setType(WemediaConstants.TYPE_SIGNAL);
                images = contentPics.stream().limit(1).collect(Collectors.toList());
            } else {
                wmNews.setType(WemediaConstants.TYPE_NO);
            }
            if (!CollectionUtils.isEmpty(images)) {
                wmNews.setImages(StringUtils.collectionToCommaDelimitedString(images));
            }
            updateById(wmNews);
        }

        if (!CollectionUtils.isEmpty(images)) {
            saveMetialRelation(wmNews, images, WemediaConstants.RFRENCE_COVER);
        }

    }

    /**
     * 保存文章内容图片与素材的关系
     *
     * @param wmNews
     * @param contentPics
     * @param type
     */
    private void saveMetialRelation(WmNews wmNews, List<String> contentPics, short type) {
        if (CollectionUtils.isEmpty(contentPics)) {
            return;
        }
        contentPics = contentPics.stream().distinct().collect(Collectors.toList());
        //查询所有的素材
        List<WmMaterial> wmMaterials = materialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, contentPics));

        List<Integer> wmMaterIds = wmMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList());

        wmNewsMaterialMapper.saveNewsMaterial(wmMaterIds, wmNews.getId(), type);
    }

    /**
     * 保存文章内容图片与素材的关系
     *
     * @param wmNews
     * @param contentPics
     */
    private void saveMetialForContent(WmNews wmNews, List<String> contentPics) {
        saveMetialRelation(wmNews, contentPics, WemediaConstants.RFRENCE_CONTENT);
    }

    /**
     * 提前文章内容中的图片
     *
     * @param content
     */
    private List<String> getContentUrl(String content) {
        List<String> pics = new ArrayList<>();
        List<Map> mapList = JSON.parseArray(content, Map.class);
        //{"type":"image","value":"xxxx"}
        for (Map map : mapList) {
            String type = map.get("type").toString();
            if ("image".equals(type)) {
                pics.add(map.get("value").toString());
            }
        }
        return pics;
    }

    /**
     * 保存或者修改
     *
     * @param newsDto
     */
    private WmNews saveOrUpdate(WmNewsDto newsDto) {
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(newsDto, wmNews);
        //处理图片,把list转成带逗号分隔的字符串
        if (!CollectionUtils.isEmpty(newsDto.getImages())) {
            wmNews.setImages(StringUtils.collectionToCommaDelimitedString(newsDto.getImages()));
        }
        //处理掉type  -1的情况
        if (newsDto.getType() == WemediaConstants.TYPE_AUTO) {
            wmNews.setType(null);
        }
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setUserId(WmThreadLocalUtil.getUser().getId());

        if (newsDto.getId() == null) {
            save(wmNews);
        } else {
            //删除关联关系
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, newsDto.getId()));
            updateById(wmNews);
        }
        return wmNews;
    }

    /**
     * 查询所有文章列表
     *
     * @param dto
     * @return
     */
    @Override
    public PageResponseResult listVo(NewsListDto dto) {
        dto.checkParam();
        PageHelper.startPage(dto.getPage(), dto.getSize());
        com.github.pagehelper.Page<WmNewsAndAuthorName> list = wmNewsMapper.listVo(dto);
        PageResponseResult result = new PageResponseResult();
        result.setSize(list.getPageSize());
        result.setCurrentPage(list.getPageNum());
        result.setTotal((int) list.getTotal());
        result.setData(list.getResult());
        return result;
    }

    /**
     * 根据id查询文章详情和作者名字
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult getOneById(Long id) {
        WmNewsAndAuthorName wmNewsAndAuthorName = wmNewsMapper.getOneById(id);
        return ResponseResult.okResult(wmNewsAndAuthorName);
    }

    /**
     * 审核成功或者失败
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult authAudit(NewsListDto dto) {
        if (ObjectUtils.isEmpty(dto)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        WmNews wmNews = new WmNews();
        wmNews.setId(Math.toIntExact(dto.getId()));
        wmNews.setStatus(dto.getStatus());
        if (!StringUtils.isEmpty(dto.getMsg())) {
            wmNews.setReason(dto.getMsg());
        }
        wmNewsMapper.updateById(wmNews);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

}